﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace MendeleyClient.Phone
{
    public class DocumentDataBroker: DataBrokerBase
    {
        DocumentViewModel paperViewModel;
        WebClient webClient;
        string uriStr = "http://api.mendeley.com/oapi/documents/details/";

        public DocumentDataBroker(DocumentViewModel paperViewModel)
        {
            this.paperViewModel = paperViewModel;
            webClient = new WebClient();
            webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient_DownloadStringCompleted);
            webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
        }

        public void GetData(string id)
        {
            if (!webClient.IsBusy)
            {
                if (id != "0")
                {
                    uriStr += ("" + id + "&" + this.consumerKeyStr);
                    webClient.DownloadStringAsync(new Uri(uriStr));
                }
            }
        }

        private void webClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            var records = DocumentRecord.Parse(e.Result.ToString());
            foreach (var record in records)
            {
                paperViewModel.Items.Add(new DocumentItemViewModel() { Title = record.title, Authors = record.authors, Value = record.value });
            }
            paperViewModel.IsDataLoaded = true;

        }

        private void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
        }
    }
}
